Page({
  data: {
    bannerList: [
      {
        id: 1,
        title: '智能化服务',
        subtitle: '专业团队 · 高效执行',
        description: '从需求分析到方案实施，全程专业服务',
        icon: '🚀',
        btnText: '立即预约',
        action: 'booking',
        bgColor: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
      },
      {
        id: 2,
        title: '数字化转型',
        subtitle: '创新驱动 · 智慧升级',
        description: '助力企业实现数字化转型升级',
        icon: '💡',
        btnText: '了解更多',
        action: 'about',
        bgColor: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)'
      },
      {
        id: 3,
        title: '全流程管控',
        subtitle: '透明可控 · 品质保障',
        description: '8步闭环管理，确保项目质量',
        icon: '🎯',
        btnText: '查看项目',
        action: 'projects',
        bgColor: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
      },
      {
        id: 4,
        title: '匠心品质',
        subtitle: '精益求精 · 追求卓越',
        description: '用匠心精神打造每一个项目',
        icon: '⭐',
        btnText: '我的订单',
        action: 'orders',
        bgColor: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
      }
    ],
          servicesList: [], // 动态从数据库加载服务网格
    productsList: [], // 动态从数据库加载
    stats: {
      totalOrders: 0,
      pendingOrders: 0,
      activeOrders: 0,
      completedOrders: 0,
      completionRate: 0,
      // 项目统计（备用）
      totalProjects: 0,
      activeProjects: 0,
      completedProjects: 0
    },
    loading: false,
    servicesLoading: true,
    productsLoading: true,
    userInfo: null,
    currentBanner: 0,
    autoPlay: true,
    
    // 搜索相关数据
    searchKeyword: '',
    showSuggestions: false,
    showSearchResults: false,
    searchSuggestions: [],
    searchResults: [],
    hotSearchTags: ['智能家居', '网络维护', '中小市场', '工程施工', '信息化集成', '计量检测'],
    recommendTags: ['智能家居', '网络维护', '工程施工', '企业资质'],
    allServices: [], // 存储所有服务数据用于搜索
    searchHistory: [], // 搜索历史
    
    // 定位相关数据
    locationInfo: {
      city: '',
      district: '',
      province: '',
      latitude: null,
      longitude: null,
      isAccurate: false
    },
    weatherInfo: {
      temperature: '',
      icon: '',
      description: ''
    },
    showCityModal: false,
    selectedCity: {},
    hotCities: [
      { code: '520100', name: '贵阳', province: '贵州省' },
      { code: '520300', name: '遵义', province: '贵州省' },
      { code: '520200', name: '六盘水', province: '贵州省' },
      { code: '520400', name: '安顺', province: '贵州省' },
      { code: '520500', name: '毕节', province: '贵州省' },
      { code: '520600', name: '铜仁', province: '贵州省' },
      { code: '522700', name: '黔南', province: '贵州省' },
      { code: '522600', name: '黔东南', province: '贵州省' },
      { code: '522300', name: '黔西南', province: '贵州省' }
    ],
    citySearchKeyword: '',
    citySearchResults: [],
    citySearchFocus: false
  },

  onLoad() {
    this.getUserInfo()
    this.loadStats()
    this.loadBanners()
    this.initShareInfo()
    this.loadServiceGrid()
    this.loadHotProducts()
    this.loadSearchHistory()
    this.loadAllServicesForSearch()
    this.initLocation()
  },

  onShow() {
    this.loadStats()
    // 刷新服务网格和产品数据
    this.loadServiceGrid()
    this.loadHotProducts()
  },

  onUnload() {
    this.stopBannerAutoPlay()
    // 清理城市搜索定时器
    if (this.citySearchTimer) {
      clearTimeout(this.citySearchTimer)
      this.citySearchTimer = null
    }
  },

  onHide() {
    this.stopBannerAutoPlay()
    // 清理城市搜索定时器
    if (this.citySearchTimer) {
      clearTimeout(this.citySearchTimer)
      this.citySearchTimer = null
    }
  },

  // 获取用户信息
  async getUserInfo() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'userManager',
        data: {
          action: 'getUserInfo'
        }
      })

      if (result.result.success) {
        this.setData({
          userInfo: result.result.userInfo
        })
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  },

  // 加载轮播图数据
  loadBanners() {
    // 启动轮播图自动播放
    this.startBannerAutoPlay()
  },

  // 初始化分享信息
  initShareInfo() {
    // 分享信息在 onShareAppMessage 和 onShareTimeline 中定义
    console.log('分享信息初始化完成')
  },

  // 加载服务网格数据
  async loadServiceGrid() {
    this.setData({ servicesLoading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'categoryManager',
        data: {
          action: 'getAllCategories'
        }
      })

      if (result.result.success && result.result.data.length > 0) {
        // 转换分类数据为服务网格格式
        const servicesList = result.result.data.map(category => ({
          id: category._id,
          key: category.code,
          name: category.name,
          icon: category.icon,
          desc: category.description,
          color: category.color,
          sortOrder: category.sortOrder
        }))
        
        this.setData({
          servicesList: servicesList,
          servicesLoading: false
        })
        console.log('✅ 服务分类加载成功，共', result.result.data.length, '项')
      } else {
        console.log('⚠️ 数据库中暂无分类数据，使用默认数据')
        this.loadDefaultServiceGrid()
      }
    } catch (error) {
      console.error('❌ 加载服务分类失败:', error)
      this.loadDefaultServiceGrid()
    }
  },

  // 降级加载默认服务网格
  loadDefaultServiceGrid() {
    console.log('使用默认服务网格')
    const defaultServices = [
      { id: 1, key: 'sme_market', name: '中小市场', icon: '🏢', desc: '市场拓展咨询' },
      { id: 2, key: 'info_integration', name: '信息化集成', icon: '💻', desc: 'ERP/CRM集成' },
      { id: 3, key: 'engineering', name: '工程施工', icon: '🏗️', desc: '项目施工管理' },
      { id: 4, key: 'network_maintenance', name: '网络维护', icon: '🔧', desc: '7x24技术支持' },
      { id: 5, key: 'smart_home', name: '智能家居', icon: '🏠', desc: '智能化解决方案' },
      { id: 6, key: 'measurement', name: '计量检测', icon: '📏', desc: '专业检测校准' },
      { id: 7, key: 'materials', name: '材料设备', icon: '📦', desc: '优质材料供应' },
      { id: 8, key: 'construction_team', name: '施工队伍', icon: '👷', desc: '专业施工团队' },
      { id: 9, key: 'qualification', name: '企业资质', icon: '📋', desc: '资质代办服务' },
      { id: 10, key: 'case_sharing', name: '案例分享', icon: '📚', desc: '成功案例展示' }
    ]
    this.setData({
      servicesList: defaultServices,
      servicesLoading: false
    })
  },



  // 加载热门产品列表
  async loadHotProducts() {
    this.setData({ productsLoading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'getHotServices',
          limit: 6
        }
      })

      if (result.result.success && result.result.data.length > 0) {
        // 直接使用云函数返回的热门服务数据
        const hotProducts = result.result.data

        this.setData({
          productsList: hotProducts,
          productsLoading: false
        })
        console.log('✅ 热门服务列表加载成功，共', hotProducts.length, '项')
      } else {
        console.log('⚠️ 数据库中暂无热门服务数据，使用默认产品列表')
        this.loadDefaultProducts()
      }
    } catch (error) {
      console.error('❌ 加载热门服务失败:', error)
      this.loadDefaultProducts()
    }
  },

  // 根据分类获取图标
  getCategoryIcon(category) {
    const iconMap = {
      'decoration': '🎨',
      'electrical': '⚡',
      'plumbing': '🚿', 
      'hvac': '❄️',
      'furniture': '🪑',
      'appliances': '📱',
      'security': '🔒',
      'cleaning': '🧹',
      'gardening': '🌱',
      'maintenance': '🔧',
      'sme_market': '🏢',
      'info_integration': '💻',
      'engineering': '🏗️',
      'network_maintenance': '🔧',
      'smart_home': '🏠',
      'measurement': '📏',
      'materials': '📦',
      'construction_team': '👷',
      'qualification': '📋'
    }
    return iconMap[category] || '🔧'
  },



  // 降级加载默认产品列表
  loadDefaultProducts() {
    console.log('使用默认产品列表')
    const defaultProducts = [
      {
        id: 'default_service_001',  // 使用字符串ID模拟MongoDB _id
        _id: 'default_service_001', // 添加_id字段
        title: '企业信息化集成方案',
        description: '为中小企业提供一站式信息化解决方案，包含ERP、CRM、OA等系统集成',
        image: 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=400&h=300&fit=crop',
        price: '8800',
        unit: '起',
        rating: '4.9',
        badge: '热销',
        tags: ['系统集成', 'ERP', 'CRM'],
        category: 'info_integration',
        serviceType: 'info_integration'
      },
      {
        id: 'default_service_002',
        _id: 'default_service_002',
        title: '智能家居系统安装',
        description: '专业智能家居系统设计安装，包含智能照明、安防、环境控制等',
        image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=300&fit=crop',
        price: '12000',
        unit: '套',
        rating: '4.8',
        badge: '推荐',
        tags: ['智能家居', '物联网', '自动化'],
        category: 'smart_home',
        serviceType: 'smart_home'
      },
      {
        id: 'default_service_003',
        _id: 'default_service_003',
        title: '网络设备维护服务',
        description: '专业网络设备巡检维护，确保企业网络稳定运行，7x24小时技术支持',
        image: 'https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=400&h=300&fit=crop',
        price: '2800',
        unit: '月',
        rating: '4.7',
        badge: '',
        tags: ['网络维护', '技术支持', '巡检'],
        category: 'network_maintenance',
        serviceType: 'network_maintenance'
      }
    ]
    this.setData({
      productsList: defaultProducts,
      productsLoading: false
    })
  },

  // 加载统计数据 - 使用云函数
  async loadStats() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      console.log('📊 开始加载统计数据...')
      const result = await wx.cloud.callFunction({
        name: 'businessManager',
        data: {
          action: 'getStats'
        }
      })

      console.log('📊 云函数返回结果:', result.result)

      if (result.result.success) {
        console.log('📊 设置统计数据:', result.result.data)
        this.setData({
          stats: result.result.data
        })
        console.log('📊 当前页面stats数据:', this.data.stats)
      } else {
        console.warn('📊 云函数统计失败，降级到本地统计')
        // 降级到本地统计
        this.loadStatsFromLocal()
      }
    } catch (error) {
      console.error('❌ 加载统计数据失败:', error)
      // 降级到本地统计
      this.loadStatsFromLocal()
    } finally {
      this.setData({ loading: false })
    }
  },

  // 降级加载本地统计数据 - 与用户订单页面统计逻辑保持一致
  loadStatsFromLocal() {
    console.log('降级使用本地存储统计')
    const orders = wx.getStorageSync('orders') || []
    const projects = wx.getStorageSync('projects') || []

    const totalOrders = orders.length
    
    // 待处理 = 待接单（waiting_team标签页逻辑）
    const pendingOrders = orders.filter(order => 
      ['pending', 'waiting_team'].includes(order.status)
    ).length
    
    // 进行中 = 已接单 + 查勘中 + 设计中 + 已报价 + 施工中 + 验收中
    const activeOrders = orders.filter(order => 
      ['accepted', 'team_accepted', 'confirmed', 'surveying', 'designing', 'quoted', 'in_progress', 'testing'].includes(order.status)
    ).length
    
    // 已完成
    const completedOrders = orders.filter(order => 
      order.status === 'completed'
    ).length
    
    // 已取消
    const cancelledOrders = orders.filter(order => 
      order.status === 'cancelled'
    ).length
    
    const activeProjects = projects.filter(p => ['planning', 'active'].includes(p.status)).length
    const completedProjects = projects.filter(p => p.status === 'completed').length
    const completionRate = totalOrders > 0 ? Math.round((completedOrders / totalOrders) * 100) : 0

    console.log('📊 首页本地统计结果:', {
      totalOrders,
      pendingOrders,
      activeOrders,
      completedOrders,
      cancelledOrders,
      completionRate
    })

    this.setData({
      stats: {
        totalOrders,
        pendingOrders,
        activeOrders,
        completedOrders,
        cancelledOrders,
        completionRate,
        // 项目统计
        totalProjects: projects.length,
        activeProjects,
        completedProjects
      }
    })
  },

  // 轮播图自动播放
  startBannerAutoPlay() {
    this.bannerTimer = setInterval(() => {
      if (!this.data.autoPlay) return
      
      const nextIndex = (this.data.currentBanner + 1) % this.data.bannerList.length
      this.setData({ currentBanner: nextIndex })
    }, 4000)
  },

  // 停止轮播图自动播放
  stopBannerAutoPlay() {
    if (this.bannerTimer) {
      clearInterval(this.bannerTimer)
      this.bannerTimer = null
    }
  },

  // 轮播图手动切换
  onBannerChange(e) {
    this.setData({
      currentBanner: e.detail.current
    })
  },

  // 暂停/恢复自动播放
  toggleAutoPlay() {
    this.setData({
      autoPlay: !this.data.autoPlay
    })
  },

  // 导航到预约页面
  goToBooking() {
    wx.navigateTo({
      url: '/pages/booking/booking'
    })
  },

  // 导航到订单页面
  goToOrders() {
    wx.switchTab({
      url: '/pages/orders/orders'
    })
  },

  // 统计项点击事件
  onStatItemTap(e) {
    const { tab } = e.currentTarget.dataset
    console.log('📊 首页统计项点击:', tab)
    
    if (tab === 'completion_rate') {
      // 完成率不跳转，只显示提示
      wx.showToast({
        title: '完成率统计',
        icon: 'none',
        duration: 1500
      })
      return
    }
    
    if (tab === 'in_progress') {
      // 进行中包含多个状态，显示选择菜单
      this.showInProgressMenu()
      return
    }
    
    // 其他统计项直接跳转到订单页面对应标签
    // 由于wx.switchTab不支持URL参数，使用全局变量传递
    getApp().globalData.targetTab = tab
    wx.switchTab({
      url: '/pages/orders/orders'
    })
  },

  // 显示进行中状态选择菜单
  showInProgressMenu() {
    const inProgressOptions = [
      { key: 'team_accepted', name: '已接单' },
      { key: 'surveying', name: '查勘中' },
      { key: 'designing', name: '设计中' },
      { key: 'quoted', name: '已报价' },
      { key: 'in_progress', name: '施工中' },
      { key: 'testing', name: '验收中' }
    ]
    
    const itemList = inProgressOptions.map(option => option.name)
    
    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        const selectedOption = inProgressOptions[res.tapIndex]
        console.log('📊 选择进行中子状态:', selectedOption)
        
        // 跳转到订单页面对应标签
        // 由于wx.switchTab不支持URL参数，使用全局变量传递
        getApp().globalData.targetTab = selectedOption.key
        wx.switchTab({
          url: '/pages/orders/orders'
        })
      },
      fail: (res) => {
        console.log('用户取消选择')
      }
    })
  },

  // 导航到项目页面
  goToProjects() {
    wx.switchTab({
      url: '/pages/projects/projects'
    })
  },

  // 导航到个人中心
  goToProfile() {
    wx.switchTab({
      url: '/pages/profile/profile'
    })
  },



  // 轮播图点击事件
  onBannerTap(e) {
    const { action } = e.currentTarget.dataset

    switch (action) {
      case 'booking':
        this.goToBooking()
        break
      case 'orders':
        this.goToOrders()
        break
      case 'projects':
        this.goToProjects()
        break
      case 'about':
        wx.navigateTo({
          url: '/pages/about/about'
        })
        break
      default:
        console.log('未知操作:', action)
    }
  },

  // 服务类型点击事件 - 跳转到服务分类页面
  onServiceTap(e) {
    const { service } = e.currentTarget.dataset
    console.log('首页服务点击:', service)
    
    if (service.key === 'case_sharing') {
      this.showCaseSharing()
    } else {
      // 跳转到服务分类页面，显示该分类下的具体服务项目
      console.log('跳转到服务分类页面，category:', service.key)
      wx.navigateTo({
        url: `/pages/service-category/service-category?category=${service.key}`
      })
    }
  },

  // 带服务类型的预约
  goToBookingWithService(serviceType) {
    wx.navigateTo({
      url: `/pages/booking/booking?serviceType=${serviceType}`
    })
  },

  // 显示案例分享
  showCaseSharing() {
    console.log('📚 从首页跳转到案例分享页面')
    wx.navigateTo({
      url: '/pages/case-sharing/case-sharing'
    })
  },

  // 产品点击事件 - 修复热门服务详情页面跳转
  onProductTap(e) {
    const { product } = e.currentTarget.dataset
    console.log('🛍️ 点击热门产品:', product)
    
    if (!product) {
      wx.showToast({
        title: '产品信息不存在',
        icon: 'none'
      })
      return
    }
    
    // 将产品数据转换为服务详情格式
    const serviceInfo = {
      _id: product._id || product.id,  // 确保_id字段存在（数据库主键）
      id: product.id || product._id,   // 兼容性字段
      title: product.title,
      description: product.description,
      image: product.image,
      price: product.price,
      unit: product.unit,
      rating: product.rating,
      badge: product.badge,
      tags: product.tags || [],
      category: product.category,
      serviceType: product.serviceType || product.category
    }
    
    console.log('🔄 转换为服务信息:', serviceInfo)
    
    // 跳转到服务详情页面（服务模式）
    const serviceData = encodeURIComponent(JSON.stringify(serviceInfo))
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?service=${serviceData}`
    })
  },

  // 显示配置指南
  showConfigGuide() {
    wx.showModal({
      title: '⚙️ 配置指南',
      content: '当前使用演示数据。\n\n要启用完整功能，请：\n1. 配置云开发环境\n2. 部署云函数\n3. 初始化数据库\n\n详见项目文档。',
      confirmText: '查看文档',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/about/about'
          })
        }
      }
    })
  },

  // 刷新数据
  onPullDownRefresh() {
    Promise.all([
      this.loadStats(),
      this.getUserInfo(),
      this.loadServiceGrid(),
      this.loadHotProducts()
    ]).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 快速操作
  quickAction(e) {
    const { action } = e.currentTarget.dataset
    
    switch (action) {
      case 'newOrder':
        this.goToBooking()
        break
      case 'viewOrders':
        this.goToOrders()
        break
      case 'viewProjects':
        this.goToProjects()
        break
      case 'contactService':
        wx.makePhoneCall({
          phoneNumber: '400-888-8888',
          fail: () => {
            wx.showToast({
              title: '拨号失败',
              icon: 'none'
            })
          }
        })
        break
      default:
        console.log('未知快速操作:', action)
    }
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '数智匠心工程 - 专业工程服务平台',
      path: '/pages/index/index',
      imageUrl: '/images/share-cover.png'
    }
  },

  onShareTimeline() {
    return {
      title: '数智匠心工程 - 专业工程服务平台',
      query: '',
      imageUrl: '/images/share-cover.png'
    }
  },

  // 显示调试菜单（已移动到个人中心）
  showDebugMenu() {
    console.log('🔧 调试菜单已移动到个人中心')

    wx.showModal({
      title: '💡 提示',
      content: '开发者工具已移动到个人中心页面。\n\n请前往：我的 → 开发工具区域',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },





  // 数据库初始化方法已移动到个人中心
  async initDatabase() {
    wx.showModal({
      title: '💡 提示',
      content: '数据库初始化功能已移动到个人中心。\n\n请前往：我的 → 开发工具区域',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 服务数据初始化方法已移动到个人中心
  async initServiceData() {
    wx.showModal({
      title: '💡 提示',
      content: '服务数据初始化功能已移动到个人中心。\n\n请前往：我的 → 开发工具区域',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 分类数据初始化方法已移动到个人中心
  async initCategoryData() {
    wx.showModal({
      title: '💡 提示',
      content: '分类数据初始化功能已移动到个人中心。\n\n请前往：我的 → 开发工具区域',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 清理测试数据方法已移动到个人中心
  async cleanTestData() {
    wx.showModal({
      title: '💡 提示',
      content: '清理测试数据功能已移动到个人中心。\n\n请前往：我的 → 开发工具区域',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 检查集合状态方法已移动到个人中心
  async checkCollectionStatus() {
    wx.showModal({
      title: '💡 提示',
      content: '检查集合状态功能已移动到个人中心。\n\n请前往：我的 → 开发工具区域',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 初始化服务数据方法已移动到个人中心
  async initServiceData() {
    wx.showModal({
      title: '💡 提示',
      content: '初始化服务数据功能已移动到个人中心。\n\n请前往：我的 → 连续点击头像5次 → 开发者菜单',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 初始化分类数据方法已移动到个人中心
  async initCategoryData() {
    wx.showModal({
      title: '💡 提示',
      content: '初始化分类数据功能已移动到个人中心。\n\n请前往：我的 → 连续点击头像5次 → 开发者菜单',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // 清理测试数据方法已移动到个人中心
  async cleanTestData() {
    wx.showModal({
      title: '💡 提示',
      content: '清理测试数据功能已移动到个人中心。\n\n请前往：我的 → 连续点击头像5次 → 开发者菜单',
      confirmText: '前往个人中心',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          })
        }
      }
    })
  },

  // ==================== 搜索功能 ====================

  // 搜索输入处理
  onSearchInput(e) {
    const keyword = e.detail.value.trim()
    this.setData({
      searchKeyword: keyword
    })

    // 防抖处理，延迟搜索建议
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      if (keyword.length > 0) {
        this.generateSearchSuggestions(keyword)
      } else {
        this.setData({
          showSuggestions: false,
          searchSuggestions: []
        })
      }
    }, 300)
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value.trim()
    if (keyword) {
      this.performSearch(keyword)
      this.addToSearchHistory(keyword)
    }
  },

  // 搜索框获得焦点
  onSearchFocus() {
    const { searchKeyword } = this.data
    if (searchKeyword.length > 0) {
      this.generateSearchSuggestions(searchKeyword)
    }
  },

  // 搜索框失去焦点
  onSearchBlur() {
    // 延迟隐藏建议，让用户有时间点击建议项
    setTimeout(() => {
      this.setData({
        showSuggestions: false
      })
    }, 200)
  },

  // 清空搜索
  onSearchClear() {
    this.setData({
      searchKeyword: '',
      showSuggestions: false,
      showSearchResults: false,
      searchSuggestions: [],
      searchResults: []
    })
    
    // 恢复页面正常状态
    this.exitSearchMode()
  },

  // 热门标签点击
  onHotTagTap(e) {
    const tag = e.currentTarget.dataset.tag
    this.setData({
      searchKeyword: tag
    })
    this.performSearch(tag)
    this.addToSearchHistory(tag)
  },

  // 搜索建议点击
  onSuggestionTap(e) {
    const suggestion = e.currentTarget.dataset.suggestion
    this.setData({
      searchKeyword: suggestion.title,
      showSuggestions: false
    })
    this.performSearch(suggestion.title)
    this.addToSearchHistory(suggestion.title)
  },

  // 搜索结果点击
  onSearchResultTap(e) {
    const item = e.currentTarget.dataset.item
    
    if (item.type === 'service') {
      // 检查是否是本地搜索结果（有fullProductInfo）
      if (item.fullProductInfo) {
        // 本地搜索结果，使用原来的id跳转方式
        wx.navigateTo({
          url: `/pages/product-detail/product-detail?id=${item.id}`
        })
      } else {
        // 云函数搜索结果，使用service参数传递完整服务信息
        const serviceInfo = {
          id: item.id,
          title: item.title,
          description: item.description,
          icon: item.icon,
          color: item.color,
          tags: item.tags,
          category: item.category,
          categoryName: item.categoryName,
          price: '面议',
          unit: '',
          rating: '4.5',
          image: 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=400&h=300&fit=crop'
        }
        
        wx.navigateTo({
          url: `/pages/product-detail/product-detail?service=${encodeURIComponent(JSON.stringify(serviceInfo))}`
        })
      }
    } else if (item.type === 'category') {
      // 跳转到分类页面
      wx.navigateTo({
        url: `/pages/service-category/service-category?category=${item.categoryCode}`
      })
    }
  },

  // 生成搜索建议
  async generateSearchSuggestions(keyword) {
    try {
      const suggestions = []
      
      // 从服务分类中搜索
      const { servicesList } = this.data
      servicesList.forEach(service => {
        if (service.name.includes(keyword) || service.desc.includes(keyword)) {
          suggestions.push({
            id: `category_${service.id}`,
            title: service.name,
            type: '服务分类',
            icon: service.icon,
            categoryCode: service.key
          })
        }
      })

      // 从所有服务中搜索
      const { allServices } = this.data
      allServices.forEach(service => {
        if (service.title && service.title.includes(keyword)) {
          suggestions.push({
            id: `service_${service.id}`,
            title: service.title,
            type: '服务项目',
            icon: service.icon || '🔧',
            serviceId: service.id
          })
        }
      })

      // 限制建议数量
      const limitedSuggestions = suggestions.slice(0, 5)
      
      this.setData({
        searchSuggestions: limitedSuggestions,
        showSuggestions: limitedSuggestions.length > 0
      })

    } catch (error) {
      console.error('生成搜索建议失败:', error)
    }
  },

  // 执行搜索
  async performSearch(keyword) {
    console.log('🔍 执行搜索:', keyword)
    
    wx.showLoading({
      title: '搜索中...',
      mask: true
    })

    try {
      // 调用搜索云函数
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'searchServices',
          keyword: keyword,
          categoryCode: '' // 不限制分类
        }
      })

      wx.hideLoading()

      if (result.result.success) {
        // 处理搜索结果数据格式
        let servicesData = []
        
        if (result.result.data && result.result.data.services) {
          // 新格式：{success: true, data: {services: [...], searchInfo: {...}}}
          servicesData = result.result.data.services
        } else if (result.result.data && Array.isArray(result.result.data)) {
          // 旧格式：{success: true, data: [...]}
          servicesData = result.result.data
        }
        
        const searchResults = servicesData.map(item => ({
          id: item._id,
          type: 'service',
          title: item.title,
          description: item.description,
          icon: item.categoryInfo?.icon || '🔧',
          color: item.categoryInfo?.color || '#667eea',
          tags: item.tags || [],
          category: item.category,
          categoryName: item.categoryInfo?.name || item.categoryName
        }))

        // 同时搜索分类
        const { servicesList } = this.data
        const categoryResults = servicesList.filter(category => 
          category.name.includes(keyword) || 
          category.desc.includes(keyword)
        ).map(category => ({
          id: category.id,
          type: 'category',
          title: category.name,
          description: category.desc,
          icon: category.icon,
          color: category.color || '#667eea',
          tags: ['服务分类'],
          categoryCode: category.key
        }))

        const allResults = [...categoryResults, ...searchResults]
        
        this.setData({
          searchResults: allResults,
          showSearchResults: true,
          showSuggestions: false
        })

        // 进入搜索模式
        this.enterSearchMode()

        console.log('✅ 搜索完成，找到', allResults.length, '项结果')
      } else {
        throw new Error(result.result.error || '搜索失败')
      }

    } catch (error) {
      wx.hideLoading()
      console.error('❌ 搜索失败:', error)
      
      // 降级到本地搜索
      this.performLocalSearch(keyword)
    }
  },

  // 本地搜索（降级方案）
  performLocalSearch(keyword) {
    console.log('📱 使用本地搜索:', keyword)
    
    const results = []
    const { servicesList, productsList } = this.data
    
    // 搜索服务分类
    servicesList.forEach(service => {
      if (service.name.includes(keyword) || service.desc.includes(keyword)) {
        results.push({
          id: service.id,
          type: 'category',
          title: service.name,
          description: service.desc,
          icon: service.icon,
          color: service.color || '#667eea',
          tags: ['服务分类'],
          categoryCode: service.key
        })
      }
    })

    // 搜索热门产品
    productsList.forEach(product => {
      if (product.title.includes(keyword) || 
          product.description.includes(keyword) ||
          (product.tags && product.tags.some(tag => tag.includes(keyword)))) {
        results.push({
          id: product.id,
          type: 'service',
          title: product.title,
          description: product.description,
          icon: '🔧',
          color: '#667eea',
          tags: product.tags || [],
          productId: product.id,
          // 添加完整的产品信息用于跳转
          fullProductInfo: product
        })
      }
    })

    this.setData({
      searchResults: results,
      showSearchResults: true,
      showSuggestions: false
    })

    this.enterSearchMode()
    
    wx.showToast({
      title: `找到 ${results.length} 项结果`,
      icon: 'success'
    })
  },

  // 进入搜索模式
  enterSearchMode() {
    // 直接设置搜索状态
    this.setData({
      searchActive: true
    })
  },

  // 退出搜索模式
  exitSearchMode() {
    this.setData({
      searchActive: false,
      showSearchResults: false,
      showSuggestions: false,
      searchSuggestions: []
    })
  },

  // 添加到搜索历史
  addToSearchHistory(keyword) {
    let { searchHistory } = this.data
    
    // 去重并添加到开头
    searchHistory = searchHistory.filter(item => item !== keyword)
    searchHistory.unshift(keyword)
    
    // 限制历史记录数量
    if (searchHistory.length > 10) {
      searchHistory = searchHistory.slice(0, 10)
    }
    
    this.setData({
      searchHistory
    })
    
    // 保存到本地存储
    try {
      wx.setStorageSync('search_history', searchHistory)
    } catch (error) {
      console.error('保存搜索历史失败:', error)
    }
  },

  // 加载搜索历史
  loadSearchHistory() {
    try {
      const history = wx.getStorageSync('search_history')
      if (history && Array.isArray(history)) {
        this.setData({
          searchHistory: history
        })
      }
    } catch (error) {
      console.error('加载搜索历史失败:', error)
    }
  },

  // 加载所有服务数据用于搜索
  async loadAllServicesForSearch() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'serviceManager',
        data: {
          action: 'getAllServices'
        }
      })

      if (result.result.success) {
        this.setData({
          allServices: result.result.data
        })
        console.log('✅ 加载搜索数据完成，共', result.result.data.length, '项服务')
      }
    } catch (error) {
      console.error('❌ 加载搜索数据失败:', error)
    }
  },

  // 初始化定位
  async initLocation() {
    console.log('🌍 初始化定位功能')
    
    // 先尝试从缓存获取位置信息
    const cachedLocation = this.getCachedLocation()
    if (cachedLocation) {
      this.setData({
        locationInfo: cachedLocation
      })
      console.log('📍 使用缓存位置:', cachedLocation.city)
    }
    
    // 获取当前位置
    await this.getCurrentLocation()
    
    // 获取天气信息
    if (this.data.locationInfo.city) {
      await this.getWeatherInfo()
    }
  },

  // 获取当前位置
  async getCurrentLocation() {
    try {
      console.log('🔄 开始获取当前位置')
      
      // 首先检查位置权限 - 使用Promise包装
      const authSetting = await new Promise((resolve, reject) => {
        wx.getSetting({
          success: resolve,
          fail: reject
        })
      })
      console.log('📋 当前授权状态:', authSetting.authSetting)
      
      if (authSetting.authSetting['scope.userLocation'] === false) {
        // 用户曾经拒绝过位置权限，需要引导用户手动开启
        console.log('❌ 用户已拒绝位置权限')
        
        const modalResult = await new Promise((resolve, reject) => {
          wx.showModal({
            title: '需要位置权限',
            content: '为了提供更精准的服务，需要获取您的位置信息。请在设置中开启位置权限。',
            confirmText: '去设置',
            cancelText: '使用默认',
            success: resolve,
            fail: reject
          })
        })
        
        if (modalResult.confirm) {
          // 打开设置页面
          await new Promise((resolve, reject) => {
            wx.openSetting({
              success: resolve,
              fail: reject
            })
          })
        }
        
        // 无论用户是否去设置，都使用默认位置
        this.setDefaultLocation()
        return null
      }
      
      // 尝试获取位置权限
      try {
        await new Promise((resolve, reject) => {
          wx.authorize({
            scope: 'scope.userLocation',
            success: resolve,
            fail: reject
          })
        })
        console.log('✅ 位置权限获取成功')
      } catch (authError) {
        console.log('❌ 位置权限获取失败:', authError)
        this.setDefaultLocation()
        return null
      }

      // 获取位置信息 - 使用Promise包装微信API
      try {
        const locationResult = await new Promise((resolve, reject) => {
          wx.getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
            highAccuracyExpireTime: 6000,  // 增加高精度定位时间
            altitude: false,                // 不需要海拔信息，提高稳定性
            success: (res) => {
              console.log('📍 wx.getLocation success:', res)
              resolve(res)
            },
            fail: (err) => {
              console.log('📍 wx.getLocation fail:', err)
              reject(err)
            }
          })
        })
        
        console.log('📍 原始位置获取成功:', locationResult)
        
        // 验证返回的数据
        if (!locationResult || typeof locationResult.latitude !== 'number' || typeof locationResult.longitude !== 'number') {
          throw new Error('位置数据格式错误')
        }
        
        // 检查是否与缓存位置相近（50米范围内）
        const cachedLocation = this.getCachedLocation()
        if (cachedLocation && this.isLocationNearby(locationResult, cachedLocation, 50)) {
          console.log('📍 位置与缓存相近，使用缓存的逆地理编码结果')
          
          // 更新坐标但保持地址信息
          const updatedLocationData = {
            ...cachedLocation,
            latitude: locationResult.latitude,
            longitude: locationResult.longitude,
            timestamp: Date.now()
          }
          
          this.setData({
            locationInfo: updatedLocationData
          })
          
          this.cacheLocation(updatedLocationData)
          return locationResult
        }
        
        // 新位置，进行逆地理编码
        await this.reverseGeocode(locationResult.latitude, locationResult.longitude)
        return locationResult
        
      } catch (locationError) {
        console.error('❌ 获取位置失败:', locationError)
        
        // 根据错误类型提供不同的提示
        if (locationError.errMsg?.includes('auth deny')) {
          wx.showToast({
            title: '位置权限被拒绝',
            icon: 'none',
            duration: 2000
          })
        } else if (locationError.errMsg?.includes('system deny')) {
          wx.showToast({
            title: '系统拒绝位置访问',
            icon: 'none',
            duration: 2000
          })
        } else if (locationError.errMsg?.includes('fail')) {
          wx.showToast({
            title: '定位服务不可用',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '定位失败，请检查网络',
            icon: 'none',
            duration: 2000
          })
        }
        
        this.setDefaultLocation()
        return null
      }
      
    } catch (error) {
      console.error('❌ 定位过程出错:', error)
      this.setDefaultLocation()
      return null
    }
  },

  // 判断两个位置是否相近（距离小于指定米数）
  isLocationNearby(location1, location2, distanceThreshold = 50) {
    if (!location1 || !location2 || !location1.latitude || !location2.latitude) {
      return false
    }
    
    const distance = this.calculateDistance(
      location1.latitude, location1.longitude,
      location2.latitude, location2.longitude
    )
    
    console.log(`📏 位置距离: ${distance.toFixed(2)}米，阈值: ${distanceThreshold}米`)
    return distance < distanceThreshold
  },

  // 计算两点间距离（米）
  calculateDistance(lat1, lng1, lat2, lng2) {
    const R = 6371000 // 地球半径（米）
    const dLat = (lat2 - lat1) * Math.PI / 180
    const dLng = (lng2 - lng1) * Math.PI / 180
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
              Math.sin(dLng / 2) * Math.sin(dLng / 2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
    return R * c
  },

  // 逆地理编码
  async reverseGeocode(latitude, longitude) {
    try {
      console.log('🔄 开始逆地理编码:', latitude, longitude)
      
      // 调用云函数进行逆地理编码
      const result = await wx.cloud.callFunction({
        name: 'locationService',
        data: {
          action: 'reverseGeocode',
          latitude: latitude,
          longitude: longitude
        }
      })

      if (result.result.success) {
        const locationData = result.result.data
        console.log('📍 逆地理编码成功:', locationData)

        // 构造标准格式的位置信息
        const standardLocationData = {
          city: locationData.city || '未知城市',
          district: locationData.district || '',
          province: locationData.province || '未知省份',
          street: locationData.street || '',
          formattedAddress: locationData.formattedAddress || '',
          latitude: latitude,
          longitude: longitude,
          isAccurate: locationData.isAccurate || true
        }

        // 构造城市选择信息
        const cityInfo = {
          code: locationData.adcode || locationData.citycode || '',
          name: locationData.city?.replace('市', '') || '未知',
          province: locationData.province || '未知省份'
        }

        this.setData({
          locationInfo: standardLocationData,
          selectedCity: cityInfo
        })

        // 缓存位置信息
        this.cacheLocation(standardLocationData)

        // 获取天气信息
        this.getWeatherInfo(latitude, longitude)
        
        console.log('📍 定位成功:', standardLocationData.city, standardLocationData.district)
      } else {
        throw new Error(result.result.error || '逆地理编码失败')
      }
    } catch (error) {
      console.error('逆地理编码失败:', error)
      
      // 如果云函数调用失败，尝试使用备用数据
      if (error.result && error.result.fallbackData) {
        const fallbackData = error.result.fallbackData
        this.setData({
          locationInfo: fallbackData,
          selectedCity: {
            code: '',
            name: fallbackData.city?.replace('市', '') || '未知',
            province: fallbackData.province || '未知省份'
          }
        })
        this.cacheLocation(fallbackData)
      } else {
        this.setDefaultLocation()
      }
    }
  },

  // 设置默认位置
  setDefaultLocation() {
    const defaultLocation = {
      city: '贵阳市',
      district: '观山湖区',
      province: '贵州省',
      latitude: null,
      longitude: null,
      isAccurate: false
    }

    this.setData({
      locationInfo: defaultLocation,
      selectedCity: {
        code: '520100',
        name: '贵阳',
        province: '贵州省'
      }
    })

    console.log('📍 使用默认位置:', defaultLocation.city)
  },

  // 缓存位置信息
  cacheLocation(locationInfo) {
    try {
      const cacheData = {
        ...locationInfo,
        timestamp: Date.now()
      }
      wx.setStorageSync('cached_location', cacheData)
    } catch (error) {
      console.error('缓存位置信息失败:', error)
    }
  },

  // 获取缓存的位置信息
  getCachedLocation() {
    try {
      const cached = wx.getStorageSync('cached_location')
      if (cached && cached.timestamp) {
        // 检查缓存是否过期（1小时）
        const now = Date.now()
        const cacheAge = now - cached.timestamp
        const maxAge = 60 * 60 * 1000 // 1小时

        if (cacheAge < maxAge) {
          return cached
        }
      }
    } catch (error) {
      console.error('获取缓存位置失败:', error)
    }
    return null
  },

  // 获取天气信息
  async getWeatherInfo(latitude, longitude) {
    try {
      console.log('🌤️ 开始获取天气信息')
      
      // 调用云函数获取天气信息
      const result = await wx.cloud.callFunction({
        name: 'locationService',
        data: {
          action: 'getWeather',
          latitude: latitude,
          longitude: longitude
        }
      })

      if (result.result.success) {
        const weatherData = result.result.data
        this.setData({
          weatherInfo: weatherData
        })
        console.log('🌤️ 天气信息获取成功:', weatherData.temperature + '°', weatherData.description)
      } else {
        throw new Error(result.result.error || '获取天气信息失败')
      }
    } catch (error) {
      console.error('获取天气信息失败:', error)
      
      // 使用默认天气信息
      const defaultWeather = {
        temperature: '--',
        icon: '🌤️',
        description: '暂无'
      }
      
      this.setData({
        weatherInfo: defaultWeather
      })
    }
  },

  // 点击位置信息
  onLocationTap() {
    console.log('📍 点击位置信息')
    this.setData({
      showCityModal: true,
      citySearchKeyword: '',     // 清空搜索关键词
      citySearchResults: [],     // 清空搜索结果
      citySearchFocus: false     // 不自动聚焦
    })
  },

  // 关闭城市选择弹窗
  onCityModalClose() {
    console.log('❌ 关闭城市选择弹窗')
    this.setData({
      showCityModal: false,
      citySearchKeyword: '',
      citySearchResults: [],
      citySearchFocus: false
    })
  },

  // 阻止弹窗内容区域的点击事件冒泡
  onModalContentTap() {
    // 阻止事件冒泡，防止弹窗关闭
    console.log('🔒 阻止弹窗内容点击冒泡')
  },

  // 搜索框聚焦事件
  onSearchInputFocus() {
    console.log('🔍 搜索框获得焦点')
    // 确保弹窗保持打开状态
    if (!this.data.showCityModal) {
      this.setData({
        showCityModal: true
      })
    }
  },

  // 搜索框失焦事件
  onSearchInputBlur() {
    console.log('🔍 搜索框失去焦点')
    // 不要在失焦时关闭弹窗
  },

  // 选择当前定位
  onSelectCurrentLocation() {
    console.log('📍 选择当前定位')
    this.onCityModalClose()
    // 重新获取位置
    this.getCurrentLocation()
  },

  // 重新定位
  async onRelocate() {
    try {
      console.log('🔄 开始重新定位')
      
      // 防抖机制：如果正在定位中，直接返回
      if (this.relocating) {
        console.log('⚠️ 正在定位中，忽略重复请求')
        wx.showToast({
          title: '正在定位中...',
          icon: 'none',
          duration: 1000
        })
        return
      }
      
      this.relocating = true
      
      // 先显示定位中状态
      this.setData({
        locationInfo: {
          city: '定位中...',
          district: '',
          province: '',
          isAccurate: false
        }
      })
      
      wx.showLoading({
        title: '正在定位...',
        mask: true
      })

      // 重新获取当前位置（会自动使用智能缓存机制）
      const location = await this.getCurrentLocation()
      
      if (location) {
        console.log('✅ 重新定位成功:', location)
        
        // 等待确保reverseGeocode完成
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 检查位置信息是否已更新
        const currentLocationInfo = this.data.locationInfo
        console.log('📍 当前页面位置信息:', currentLocationInfo)
        
        // 如果reverseGeocode失败，手动设置位置信息
        if (!currentLocationInfo.city || currentLocationInfo.city === '' || currentLocationInfo.city === '定位中...') {
          console.log('⚠️ 逆地理编码可能失败，使用坐标信息')
          
          const coordinateLocationInfo = {
            city: '定位成功',
            district: `坐标: ${location.latitude.toFixed(4)}, ${location.longitude.toFixed(4)}`,
            province: '精确位置',
            latitude: location.latitude,
            longitude: location.longitude,
            isAccurate: true,
            timestamp: Date.now()
          }
          
          this.setData({
            locationInfo: coordinateLocationInfo
          })
          
          // 缓存坐标位置信息
          this.cacheLocation(coordinateLocationInfo)
        }
        
        // 重新加载基于位置的数据
        this.loadServiceGrid()
        this.loadHotProducts()

        // 关闭弹窗
        this.onCityModalClose()

        wx.hideLoading()
        
        // 显示定位成功的具体位置
        const finalLocationInfo = this.data.locationInfo
        const locationText = finalLocationInfo?.city ? 
          `${finalLocationInfo.city}${finalLocationInfo.district ? ' ' + finalLocationInfo.district : ''}` : 
          '当前位置'
          
        wx.showToast({
          title: `${locationText}`,
          icon: 'success',
          duration: 2000
        })

        console.log('✅ 重新定位完成，最终位置信息:', this.data.locationInfo)

      } else {
        wx.hideLoading()
        
        // 定位失败，恢复之前的位置或使用默认位置
        const cachedLocation = this.getCachedLocation()
        if (cachedLocation) {
          this.setData({
            locationInfo: cachedLocation
          })
        } else {
          this.setDefaultLocation()
        }
        
        wx.showToast({
          title: '定位失败，请检查位置权限',
          icon: 'none',
          duration: 2000
        })
      }

    } catch (error) {
      console.error('❌ 重新定位失败:', error)
      wx.hideLoading()
      
      // 定位失败，恢复之前的位置或使用默认位置
      const cachedLocation = this.getCachedLocation()
      if (cachedLocation) {
        this.setData({
          locationInfo: cachedLocation
        })
      } else {
        this.setDefaultLocation()
      }
      
      wx.showToast({
        title: '定位失败',
        icon: 'error'
      })
    } finally {
      // 重置定位状态
      this.relocating = false
    }
  },

  // 选择城市
  onSelectCity(e) {
    try {
      const city = e.currentTarget.dataset.city
      console.log('🏙️ 选择城市:', city)
      
      if (!city) {
        console.error('❌ 城市数据为空')
        wx.showToast({
          title: '城市数据错误',
          icon: 'error'
        })
        return
      }

      // 构建完整的位置信息
      const locationInfo = {
        city: city.name,
        district: city.parent || city.name,
        province: city.province,
        address: `${city.province}${city.parent ? city.parent : ''}${city.name}`,
        formatted_address: `${city.province}${city.parent ? city.parent : ''}${city.name}`,
        adcode: city.code,
        citycode: city.code.substring(0, 4) + '00',
        latitude: null,
        longitude: null,
        isAccurate: false
      }

      console.log('📍 构建的位置信息:', locationInfo)

      // 更新页面数据（同时更新多个可能的字段）
      this.setData({
        locationInfo: locationInfo,
        currentLocation: locationInfo,
        selectedCity: city,
        citySearchKeyword: '',
        citySearchResults: []
      })

      // 缓存位置信息
      this.cacheLocation(locationInfo)

      // 重新加载基于位置的数据
      this.loadServiceGrid()
      this.loadHotProducts()

      // 获取天气信息
      this.getWeatherInfo()

      // 关闭弹窗
      this.onCityModalClose()

      // 显示成功提示
      const displayName = city.parent ? `${city.parent}${city.name}` : city.name
      wx.showToast({
        title: `已切换到${displayName}`,
        icon: 'success',
        duration: 2000
      })

      console.log('✅ 城市切换成功:', displayName)

    } catch (error) {
      console.error('❌ 选择城市失败:', error)
      wx.showToast({
        title: '切换城市失败',
        icon: 'error'
      })
    }
  },

  // 城市搜索输入
  onCitySearchInput(e) {
    try {
      const keyword = e.detail.value
      console.log('🔍 城市搜索输入:', keyword)
      
      this.setData({
        citySearchKeyword: keyword
      })

      // 清除之前的搜索定时器
      if (this.citySearchTimer) {
        clearTimeout(this.citySearchTimer)
      }

      if (keyword && keyword.trim()) {
        // 使用防抖，避免频繁搜索
        this.citySearchTimer = setTimeout(() => {
          this.searchCities(keyword.trim())
        }, 300) // 300ms防抖
      } else {
        this.setData({
          citySearchResults: []
        })
      }
    } catch (error) {
      console.error('城市搜索输入处理失败:', error)
      // 不要让错误导致弹窗关闭
    }
  },

  // 城市搜索确认（用户按回车或点击完成）
  onCitySearchConfirm(e) {
    try {
      const keyword = e.detail.value.trim()
      console.log('🔍 城市搜索确认:', keyword)
      
      if (keyword) {
        this.searchCities(keyword)
      }
    } catch (error) {
      console.error('城市搜索确认处理失败:', error)
    }
  },

  // 搜索城市
  async searchCities(keyword) {
    try {
      console.log('🔍 开始搜索城市:', keyword)
      
      // 防止空搜索
      if (!keyword || !keyword.trim()) {
        console.log('⚠️ 搜索关键词为空，清空结果')
        this.setData({
          citySearchResults: []
        })
        return
      }
      
      // 扩展的贵州城市数据，包含所有县市区
      const guizhouCities = [
        // 贵阳市
        { code: '520100', name: '贵阳市', province: '贵州省', type: 'city' },
        { code: '520102', name: '南明区', province: '贵州省', type: 'district', parent: '贵阳市' },
        { code: '520103', name: '云岩区', province: '贵州省', type: 'district', parent: '贵阳市' },
        { code: '520111', name: '花溪区', province: '贵州省', type: 'district', parent: '贵阳市' },
        { code: '520112', name: '乌当区', province: '贵州省', type: 'district', parent: '贵阳市' },
        { code: '520113', name: '白云区', province: '贵州省', type: 'district', parent: '贵阳市' },
        { code: '520115', name: '观山湖区', province: '贵州省', type: 'district', parent: '贵阳市' },
        { code: '520121', name: '开阳县', province: '贵州省', type: 'county', parent: '贵阳市' },
        { code: '520122', name: '息烽县', province: '贵州省', type: 'county', parent: '贵阳市' },
        { code: '520123', name: '修文县', province: '贵州省', type: 'county', parent: '贵阳市' },
        { code: '520181', name: '清镇市', province: '贵州省', type: 'city', parent: '贵阳市' },
        
        // 遵义市
        { code: '520300', name: '遵义市', province: '贵州省', type: 'city' },
        { code: '520302', name: '红花岗区', province: '贵州省', type: 'district', parent: '遵义市' },
        { code: '520303', name: '汇川区', province: '贵州省', type: 'district', parent: '遵义市' },
        { code: '520304', name: '播州区', province: '贵州省', type: 'district', parent: '遵义市' },
        { code: '520322', name: '桐梓县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520323', name: '绥阳县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520324', name: '正安县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520325', name: '道真县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520326', name: '务川县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520327', name: '凤冈县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520328', name: '湄潭县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520329', name: '余庆县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520330', name: '习水县', province: '贵州省', type: 'county', parent: '遵义市' },
        { code: '520381', name: '赤水市', province: '贵州省', type: 'city', parent: '遵义市' },
        { code: '520382', name: '仁怀市', province: '贵州省', type: 'city', parent: '遵义市' },
        
        // 六盘水市
        { code: '520200', name: '六盘水市', province: '贵州省', type: 'city' },
        { code: '520201', name: '钟山区', province: '贵州省', type: 'district', parent: '六盘水市' },
        { code: '520203', name: '六枝特区', province: '贵州省', type: 'district', parent: '六盘水市' },
        { code: '520221', name: '水城区', province: '贵州省', type: 'district', parent: '六盘水市' },
        { code: '520281', name: '盘州市', province: '贵州省', type: 'city', parent: '六盘水市' },
        
        // 安顺市
        { code: '520400', name: '安顺市', province: '贵州省', type: 'city' },
        { code: '520402', name: '西秀区', province: '贵州省', type: 'district', parent: '安顺市' },
        { code: '520403', name: '平坝区', province: '贵州省', type: 'district', parent: '安顺市' },
        { code: '520422', name: '普定县', province: '贵州省', type: 'county', parent: '安顺市' },
        { code: '520423', name: '镇宁县', province: '贵州省', type: 'county', parent: '安顺市' },
        { code: '520424', name: '关岭县', province: '贵州省', type: 'county', parent: '安顺市' },
        { code: '520425', name: '紫云县', province: '贵州省', type: 'county', parent: '安顺市' },
        
        // 毕节市（包含大方县）
        { code: '520500', name: '毕节市', province: '贵州省', type: 'city' },
        { code: '520502', name: '七星关区', province: '贵州省', type: 'district', parent: '毕节市' },
        { code: '520521', name: '大方县', province: '贵州省', type: 'county', parent: '毕节市' },
        { code: '520522', name: '黔西市', province: '贵州省', type: 'city', parent: '毕节市' },
        { code: '520523', name: '金沙县', province: '贵州省', type: 'county', parent: '毕节市' },
        { code: '520524', name: '织金县', province: '贵州省', type: 'county', parent: '毕节市' },
        { code: '520525', name: '纳雍县', province: '贵州省', type: 'county', parent: '毕节市' },
        { code: '520526', name: '威宁县', province: '贵州省', type: 'county', parent: '毕节市' },
        { code: '520527', name: '赫章县', province: '贵州省', type: 'county', parent: '毕节市' },
        { code: '520528', name: '百里杜鹃管理区', province: '贵州省', type: 'management_area', parent: '毕节市' },
        
        // 铜仁市
        { code: '520600', name: '铜仁市', province: '贵州省', type: 'city' },
        { code: '520602', name: '碧江区', province: '贵州省', type: 'district', parent: '铜仁市' },
        { code: '520603', name: '万山区', province: '贵州省', type: 'district', parent: '铜仁市' },
        { code: '520621', name: '江口县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520622', name: '玉屏县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520623', name: '石阡县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520624', name: '思南县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520625', name: '印江县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520626', name: '德江县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520627', name: '沿河县', province: '贵州省', type: 'county', parent: '铜仁市' },
        { code: '520628', name: '松桃县', province: '贵州省', type: 'county', parent: '铜仁市' },
        
        // 黔西南州
        { code: '522300', name: '黔西南州', province: '贵州省', type: 'prefecture' },
        { code: '522301', name: '兴义市', province: '贵州省', type: 'city', parent: '黔西南州' },
        { code: '522302', name: '兴仁市', province: '贵州省', type: 'city', parent: '黔西南州' },
        { code: '522323', name: '普安县', province: '贵州省', type: 'county', parent: '黔西南州' },
        { code: '522324', name: '晴隆县', province: '贵州省', type: 'county', parent: '黔西南州' },
        { code: '522325', name: '贞丰县', province: '贵州省', type: 'county', parent: '黔西南州' },
        { code: '522326', name: '望谟县', province: '贵州省', type: 'county', parent: '黔西南州' },
        { code: '522327', name: '册亨县', province: '贵州省', type: 'county', parent: '黔西南州' },
        { code: '522328', name: '安龙县', province: '贵州省', type: 'county', parent: '黔西南州' },
        
        // 黔东南州
        { code: '522600', name: '黔东南州', province: '贵州省', type: 'prefecture' },
        { code: '522601', name: '凯里市', province: '贵州省', type: 'city', parent: '黔东南州' },
        { code: '522622', name: '黄平县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522623', name: '施秉县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522624', name: '三穗县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522625', name: '镇远县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522626', name: '岑巩县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522627', name: '天柱县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522628', name: '锦屏县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522629', name: '剑河县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522630', name: '台江县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522631', name: '黎平县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522632', name: '榕江县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522633', name: '从江县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522634', name: '雷山县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522635', name: '麻江县', province: '贵州省', type: 'county', parent: '黔东南州' },
        { code: '522636', name: '丹寨县', province: '贵州省', type: 'county', parent: '黔东南州' },
        
        // 黔南州
        { code: '522700', name: '黔南州', province: '贵州省', type: 'prefecture' },
        { code: '522701', name: '都匀市', province: '贵州省', type: 'city', parent: '黔南州' },
        { code: '522702', name: '福泉市', province: '贵州省', type: 'city', parent: '黔南州' },
        { code: '522722', name: '荔波县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522723', name: '贵定县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522725', name: '瓮安县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522726', name: '独山县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522727', name: '平塘县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522728', name: '罗甸县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522729', name: '长顺县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522730', name: '龙里县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522731', name: '惠水县', province: '贵州省', type: 'county', parent: '黔南州' },
        { code: '522732', name: '三都县', province: '贵州省', type: 'county', parent: '黔南州' },
        
        // 新设区域
        // 贵安新区（国家级新区）
        { code: '520900', name: '贵安新区', province: '贵州省', type: 'newarea' },
        { code: '520901', name: '贵安新区直管区', province: '贵州省', type: 'district', parent: '贵安新区' }
      ]

      // 本地搜索
      const localResults = guizhouCities.filter(city => 
        city.name.includes(keyword) || 
        city.province.includes(keyword) ||
        (city.parent && city.parent.includes(keyword))
      ).slice(0, 15) // 增加显示数量

      // 立即显示本地搜索结果
      this.setData({
        citySearchResults: localResults
      })
      
      console.log('✅ 本地搜索成功:', localResults.length + '个结果')

      // 尝试调用云函数获取更完整的结果（可选）
      try {
        const result = await wx.cloud.callFunction({
          name: 'locationService',
          data: {
            action: 'searchCities',
            keyword: keyword
          }
        })

        if (result.result && result.result.success && result.result.data) {
          const cloudResults = result.result.data.slice(0, 15)
          // 如果云函数返回了更多结果，使用云函数结果
          if (cloudResults.length > localResults.length) {
            this.setData({
              citySearchResults: cloudResults
            })
            console.log('✅ 云函数搜索成功，更新结果:', cloudResults.length + '个结果')
          }
        }
      } catch (cloudError) {
        console.log('⚠️ 云函数搜索失败，继续使用本地结果:', cloudError.message)
        // 不抛出错误，继续使用本地结果
      }
      
    } catch (error) {
      console.error('❌ 搜索失败:', error)
      
      // 确保即使出错也不会导致弹窗关闭
      this.setData({
        citySearchResults: []
      })
    }
  }
})